import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

import { IWxConfig } from 'app/shared/model/wx-config.model';
import { WxConfigService } from './wx-config.service';

@Component({
    selector: 'app-wx-config-update',
    templateUrl: './wx-config-update.component.html'
})
export class WxConfigUpdateComponent implements OnInit {
    private _wxConfig: IWxConfig;
    isSaving: boolean;

    constructor(private wxConfigService: WxConfigService, private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({ wxConfig }) => {
            this.wxConfig = wxConfig;
        });
    }

    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        if (this.wxConfig.id !== undefined) {
            this.subscribeToSaveResponse(this.wxConfigService.update(this.wxConfig));
        } else {
            this.subscribeToSaveResponse(this.wxConfigService.create(this.wxConfig));
        }
    }

    private subscribeToSaveResponse(result: Observable<HttpResponse<IWxConfig>>) {
        result.subscribe((res: HttpResponse<IWxConfig>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    private onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    private onSaveError() {
        this.isSaving = false;
    }
    get wxConfig() {
        return this._wxConfig;
    }

    set wxConfig(wxConfig: IWxConfig) {
        this._wxConfig = wxConfig;
    }
}
